//
//  NSObject+HDCacheTool.m
//  CashLoan
//
//  Created by kopuCoder on 16/12/2.
//  Copyright © 2016年 kopuCoder. All rights reserved.
//

#import "NSObject+HDCacheTool.h"

/**在沙盒缓存目录下创建文件 --->Library/Caches */
#define kLocalFILEPATH(string)  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:string]

@implementation NSObject(HDCacheTool)


#pragma mark ---工具---
/**归档存值*/
+ (void)cacheData:(id )data withCacheKey:(NSString *)key{
    
    if(!data) return;
    NSString * path = [self getFilePathWithKey:key];
    
    if(path.length>0&&data){
        [NSKeyedArchiver archiveRootObject:data toFile:path];
    }
}


/**根据key 创建本地缓存路径*/
+ (NSString *)getFilePathWithKey:(NSString *)key{
    if(!key||key.length == 0) return nil;
    
    NSString * fileSuff = [NSString stringWithFormat:@"%@.caches",key];
    if(fileSuff.length == 0) return nil;
    NSString * path = kLocalFILEPATH(fileSuff);
    if(path.length == 0) return nil;
    return path;
}

/**解归档 取值*/
+ (id )getCacheDataWithCacheKey:(NSString *)key{
    NSString * path = [self getFilePathWithKey:key];
    
    if(path.length == 0) return nil;
    
    return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

/**移除操作*/
static NSFileManager * fileManager = nil;
+ (void)wipeCacheDataWithKey:(NSString *)key{
    
    GYNLog(@"fileManager:%p",fileManager);
    
    if(nil == fileManager){
        fileManager = [NSFileManager defaultManager];
    }
    NSString * path = [NSObject getFilePathWithKey:key];
    if(path.length == 0) return;
    if([fileManager fileExistsAtPath:path]){
        NSError * error = nil;
        [fileManager removeItemAtPath:path error:&error];
        if(error){
            GYNLog(@"删除失败:key:%@<--->path:%@",key,path);
        }
    }
}

@end
